<template>
<h1 style="color: orange">{{content.id==null?'发布内容页面':'修改内容页面'}}</h1>
  <el-form label-width="100px">
    <el-form-item label="文章标题">
      <el-input v-model="content.title" placeholder="请输入文章标题"></el-input>
    </el-form-item>
    <el-form-item label="文章分类">
      <el-radio-group :disabled="content.id!=null" v-model="content.type" @change="typeChange()">
        <el-radio-button v-for="c in typeArr" :label="c.type">{{c.name}}</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select v-model="content.categoryId" placeholder="请选择">
        <el-option v-for="c in categoryArr" :label="c.name" :value="c.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="封面">
      <img v-if="content.id!=null&&fileList.length==0"
           :src="'http://localhost:8080'+content.imgUrl"
           style="width: 148px;height: 148px;">
      <!--   上传组件开始   -->
      <el-upload
          name="file"
          :limit="1"
          v-model:file-list="fileList"
          action="http://localhost:8080/v1/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--   上传组件结束   -->
    </el-form-item>
    <el-form-item v-show="content.type==2" label="视频">
      <video v-if="content.id!=null&&videoFileList.length==0"
             :src="'http://localhost:8080'+content.videoUrl"
             style="width: 200px"
              type="video/mp4" controls></video>
      <!--   上传组件开始   -->
      <el-upload
          name="file"
          :limit="1"
          v-model:file-list="videoFileList"
          action="http://localhost:8080/v1/upload"
          accept="video/*"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
       <el-button>点击上传视频</el-button>
        <div>只能上传mp4文件,且不超过100MB</div>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--   上传组件结束   -->
    </el-form-item>
    <el-form-item v-show="content.type!=2" label="文章内容"><div ref="editorContent"></div></el-form-item>
    <el-form-item>
      <el-button type="primary" @click="post()">{{content.id==null?'发布内容':'修改内容'}}</el-button>
    </el-form-item>
  </el-form>
</template>

<script  setup>
import {onMounted, ref} from 'vue'
import Editor from 'wangeditor';//导入富文本编辑器   安装指令: npm install wangeditor
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";

const videoFileList = ref([]);

const post = ()=>{
  //得到当前登录的用户信息
  let user = localStorage.user?JSON.parse(localStorage.user):null;
  if (user==null){
    alert("请先登录!")
    router.push('/login');
    return;
  }
  content.value.userId = user.id;//设置当前登录的用户为作者
  if (content.value.title==''){ElMessage.error("请输入标题!");return;}
  if (content.value.categoryId==''){ElMessage.error("请选择二级分类!");return;}

  //取出选择的图片路径赋值给content
  if (content.value.id==null){//发布
    if (fileList.value.length==0){ElMessage.error("请选择封面!");return;}
    content.value.imgUrl = fileList.value[0].response.data;
  }else{//修改
    if (fileList.value.length>0){//修改图片
      content.value.imgUrl = fileList.value[0].response.data;
    }
  }


  if (content.value.type==2){//发视频
    if (videoFileList.value.length==0){ElMessage.error("请上传视频!");return;}
    content.value.videoUrl = videoFileList.value[0].response.data;
  }else{
    //得到富文本编辑器中的内容  editor.txt.html()得到html内容
    content.value.content = editor.txt.html();
    //从富文本编辑器中取出纯文本内容 截取前30个字符作为摘要内容
    content.value.brief = editor.txt.text().slice(0,30);
  }

  //把content转成查询字符串格式
  let data = qs.stringify(content.value);
  axios.post('http://localhost:8080/v1/contents/add-new',data)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success(content.value.id==null?"发布完成!":"修改完成!");
      //是修改并且来自后台管理页面的话 跳转回后台页面
      if (content.value.id!=null&&localStorage.from=='admin'){
        localStorage.from='';//把记录的修改来源信息 清除
        router.push('/admin/content');
      }else{
        router.push('/personal/management');
      }
    }
  })




}
const editorContent = ref(null);//此变量指向页面中的div
let editor = null;

//定义内容对象
const content = ref({title:'',type:'1',categoryId:'',imgUrl:null,content:''});


const typeArr = ref([]);
const categoryArr = ref([]);

const typeChange = ()=>{
  content.value.categoryId=''; //清除之前选择的二级分类(因为一级分类已经改变了)
  //发请求获取二级分类数据
  axios.get('http://localhost:8080/v1/categories/'+content.value.type+'/sub')
      .then((response)=>{
        if (response.data.code==2001){
          categoryArr.value = response.data.data;
        }
      })
}
//onMounted方法是VUE生命周期方法(从VUE实例初始化到销毁过程中自动调用的方法)
//此方法是在Vue实例挂载到页面之后自动调用的方法(可以理解为页面加载完成后调用)
onMounted(()=>{
  //判断地址栏中是否有id,有则是修改,没有是添加 http://localhost:8080/personal/post?id=18
  if (location.search.includes('id')){
    //从地址栏中得到id
    let id = new URLSearchParams(location.search).get('id');
    //发请求
    axios.get('http://localhost:8080/v1/contents/'+id+"/update")
    .then((response)=>{
      if (response.data.code==2001){
        content.value = response.data.data;
        if (content.value.type!=2){
          //如果不是视频则把查询到的正文内容设置给富文本编辑器
          editor.txt.html(content.value.content);
        }


        //发请求获取二级分类数据
        axios.get('http://localhost:8080/v1/categories/'+content.value.type+'/sub')
            .then((response)=>{
              if (response.data.code==2001){
                categoryArr.value = response.data.data;
              }
            })
      }
    })
  }


  //发请求获取二级分类数据
  axios.get('http://localhost:8080/v1/categories/1/sub')
      .then((response)=>{
        if (response.data.code==2001){
          categoryArr.value = response.data.data;
        }
      })
  //发请求获取一级分类的数据
  axios.get('http://localhost:8080/v1/categories/type').then((response)=>{
    if (response.data.code==2001){
      typeArr.value = response.data.data;
    }
  })
  //初始化富文本编辑器  editorContent.value代表页面中的div
  // (如果代码写在onMounted方法的外面,此变量得不到页面的div元素,
  // 因为vue实例和页面还没有关联)
  editor = new Editor(editorContent.value);
  editor.config.placeholder="请输入内容详情...";
  editor.create();//将富文本编辑器 渲染到页面的div里面
})
/*上传组件开始*/
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove = (uploadFile, uploadFiles) => {
  axios.post('http://localhost:8080/v1/remove?imgUrl='+uploadFile.response.data)
  .then((response)=>{
    if (response.data.code==2001){
      ElMessage.success("服务器文件删除完成!");
    }
  })
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
/*上传组件结束*/

/*富文本编辑器相关开始    需要停止工程安装wangeditor  安装指令:npm install wangeditor*/


/*富文本编辑器相关结束*/


</script>

<style scoped>

</style>